package com.example.springboottest.example.thread;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务的异常不会抛出，一个定时任务的异常不会影响别的定时任务，但导致定时任务不再执行，所以需要捕获异常，如TaskB
 */
public class ScheduledTaskTest {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService timer = Executors
                .newSingleThreadScheduledExecutor();
        timer.scheduleWithFixedDelay(new TaskA(), 0, 1, TimeUnit.SECONDS);
        timer.scheduleWithFixedDelay(new TaskB(), 2, 2, TimeUnit.SECONDS);
    }
}

class TaskA implements Runnable {
    @Override
    public void run() {
        System.out.println("taskA");
    }
}

class TaskB implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("taskB");
            throw new RuntimeException();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}